package com.kerbores.blog.module.admin;

import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.mvc.View;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Attr;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.GET;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.view.ServerRedirectView;

import com.kerbores.blog.bean.User;
import com.kerbores.blog.bean.User.Level;
import com.kerbores.blog.constant.Constant;
import com.kerbores.blog.filter.AdminFilter;
import com.kerbores.blog.module.common.BaseModule;
import com.kerbores.blog.service.IArticleService;
import com.kerbores.blog.service.IChartsService;
import com.kerbores.blog.service.INoteService;
import com.kerbores.blog.service.IUserService;
import com.kerbores.utils.entries.OperationState;
import com.kerbores.utils.entries.Result;

/**
 * @author 贵源 <br>
 *         create at 2014年10月23日
 */
@At("admin")
public class AdminModule extends BaseModule {
	@Inject
	private IUserService userService;
	@Inject
	private INoteService noteService;
	@Inject
	private IArticleService articleService;
	@Inject
	private IChartsService chartsService;
	
	@At("/")
	@Ok("forward:/admin/login")
	public Result admin() {
		return Result.success();
	}

	@At("/login")
	@GET
	public View login(@Attr("loginUser") User user) {
		if (user != null && user.getLevel() == Level.ADMIN) {// 如果是管理员
			return new ServerRedirectView("/admin/main");// 跳转到admin的主界面
		}
		return _renderVelocity("/admin/login.vm", Result.success().setTitle("管理登录"));
	}

	@At("/doLogin")
	@POST
	public View doLogin(String userName, String password) {
		Result result = userService.adminLogin(userName, password);
		if (result.getOperationState() == OperationState.SUCCESS) {
			_putSession(Constant.LOGIN_USER_SESSION_KEY, result.getData().get(Constant.LOGIN_USER_SESSION_KEY));
			return new ServerRedirectView("/admin/main");
		}
		return _renderVelocity("/admin/login.vm", result.setTitle("管理登录"));
	}

	@At("/main")
	@Ok("vel:admin/main.vm")
	@Filters(@By(type = AdminFilter.class))
	public Result main() {
		data.put("notes", noteService.loadNew());
		data.put("articles", articleService.loadNew());
		data.put("charts", chartsService.run());
		return Result.success(data);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.kerbores.blog.module.common.BaseModule#_getNameSpace()
	 */
	@Override
	public String _getNameSpace() {
		return "admin";
	}

}
